package com.sdgs.paas.sdk.core.utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sdgs.paas.sdk.core.web.loadbalance.PaasLoadBalanceConfig;

/**
 * JSON工具类
 *
 * @author wjj
 *
 */
public class JSONUtils {

    private final static ObjectMapper objectMapper = new ObjectMapper();

    private JSONUtils() {

    }

    public static ObjectMapper getInstance() {

        return objectMapper;
    }

    /**
     * javaBean,list,array convert to json string
     */
    public static String obj2json(Object obj) throws Exception {
        return objectMapper.writeValueAsString(obj);
    }

    /**
     * json string convert to javaBean
     */
    public static <T> T json2pojo(String jsonStr, Class<T> clazz)
            throws Exception {
        return objectMapper.readValue(jsonStr, clazz);
    }
    
    /**
     * json byte[] convert to javaBean
     */
    public static <T> T json2pojo(byte[] src,  TypeReference<?> valueTypeRef)
            throws Exception {
        return objectMapper.readValue(src, valueTypeRef);
    }

    /**
     * json string convert to map
     */
    @SuppressWarnings("unchecked")
	public static <T> Map<String, Object> json2map(String jsonStr)
            throws Exception {
        return objectMapper.readValue(jsonStr, Map.class);
    }

    /**
     * json string convert to map with javaBean
     */
    public static <T> Map<String, T> json2map(String jsonStr, Class<T> clazz)
            throws Exception {
        Map<String, Map<String, Object>> map = objectMapper.readValue(jsonStr,
                new TypeReference<Map<String, T>>() {
                });
        Map<String, T> result = new HashMap<String, T>();
        for (Entry<String, Map<String, Object>> entry : map.entrySet()) {
            result.put(entry.getKey(), map2pojo(entry.getValue(), clazz));
        }
        return result;
    }

    /**
     * json array string convert to list with javaBean
     */
    public static <T> List<T> json2list(String jsonArrayStr, Class<T> clazz)
            throws Exception {
        List<Map<String, Object>> list = objectMapper.readValue(jsonArrayStr,
                new TypeReference<List<T>>() {
                });
        List<T> result = new ArrayList<T>();
        for (Map<String, Object> map : list) {
            result.add(map2pojo(map, clazz));
        }
        return result;
    }

    /**
     * map convert to javaBean
     */
    public static <T> T map2pojo(Map<?,?> map, Class<T> clazz) {
        return objectMapper.convertValue(map, clazz);
    }
    
    /**
     * map to json string
     * @throws JsonProcessingException 
     */
    public static String map2json(Map<?,?> map) throws JsonProcessingException {
        return objectMapper.writeValueAsString(map);
    }
    
    public static void main(String ...args) throws Exception{
		long start = System.currentTimeMillis();
//		PaasLoadBalanceConfig config=new PaasLoadBalanceConfig();
//		List<ConditionRoute> lbtable=new ArrayList<>();
//		ConditionRoute c1=new ConditionRoute();
//		c1.setCondition("{{Traceid}}==123 || {{Traceid}}==321");
//		c1.setOrder(1);
//		Map<String, String> route1=new HashMap<>();
//		route1.put("dev-1-0", "10");
//		route1.put("dev-1-1", "90");
//		c1.setRoute(route1);
//		lbtable.add(c1);
//		
//
//		ConditionRoute c2=new ConditionRoute();
//		c2.setCondition("{{Traceid}}==789 || {{System}}=='CRM'");
//		c2.setOrder(2);
//		Map<String, String> route2=new HashMap<>();
//		route2.put("dev-1-0", "5");
//		route2.put("dev-1-1", "5");
//		c2.setRoute(route2);
//		lbtable.add(c2);
//		
//		config.setLbtable(lbtable);
//		String  lbtableStr=JSONUtils.obj2json(config);
//		PaasLoadBalanceConfig newcfg = JSONUtils.json2pojo(lbtableStr, PaasLoadBalanceConfig.class);
		
		PaasLoadBalanceConfig config;
		String lbtableStr= "{\"lbtable\":["
				+ "{\"condition\": \"{{Traceid}}==123 || {{Traceid}}==321\",\"order\": \"1\",\"route\":{\"dev-1-0\": \"10\",\"dev-1-1\": \"90\"}},"
				+ "{\"condition\": \"{{Traceid}}==789 || {{System}}=='CRM'\",\"order\": \"2\",\"route\":{\"dev-1-0\": \"5\",\"dev-1-1\": \"5\"}}"
				+ "]}";
		try {
			config = JSONUtils.json2pojo(lbtableStr, PaasLoadBalanceConfig.class);
		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println(String.format("路由配置：%s，json转对象执行耗时：%s", lbtableStr, System.currentTimeMillis() - start));
    }
}